package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;


@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     * <p>
     * 员工登录接口工作流程：
     * 1.表现层传过来DTO，先取出用户名和密码，再根据用户名将员工信息查出来
     * 2.判断 是否不存在此员工，否则抛出异常，这里处理异常的方法是实现声明一个异常类extends一下 BaseException(继承了RunningException) 异常，
     * 让这些类都变成 异常类，相当于将异常划分的更细一点儿，全局异常处理器中拦截到的是BaseException，所以会拦截这些异常
     * 这里的密码比对是把密码与从数据库里查出来的密码比较，这样便于添加加密算法
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {

        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes()); //将密码进行MD5加密后与数据库中的密码比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * <p>
     * 这里面要处理一下一个异常，就是用户名重复的时候SQL抛出的：SQLIntegrityConstraintViolationException
     * 要在全局异常处理器里面捕获这种异常，并将错误返回给前端
     * <p>
     * 这里面就直接捕获异常就行了，没必要在插入前校验数据
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        log.info("当前线程的id：" + Thread.currentThread().getId());

        //前端页面传进来的虽然是一个DTO,但这个DTO对象跟数据库表字段不匹配，要转换成实体对象
        Employee employee = new Employee();

        //前一个是源对象，后一个是目标对象
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置账号状态        1.表示正常 ， 0.表示锁定
        employee.setStatus(StatusConstant.ENABLE);

        //设置默认密码为123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //完善用户表信息
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());

        //设置操作人信息ID
        // TODO后面要完善
        //employee.setCreateUser(BaseContext.getCurrentId());
        //employee.setUpdateUser(BaseContext.getCurrentId());


        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //使用pageHelper插件进行分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        Long total = page.getTotal();
        List<Employee> employeeList = page.getResult();

        PageResult pageResult = new PageResult(total, employeeList);

        return pageResult;
    }

    /**
     * 启用或禁用员工账号
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                //.updateTime(LocalDateTime.now())
                //.updateUser(BaseContext.getCurrentId())
                .build();

        //用实体类封装数据，做修改操作

//        //设置当前操作员工
//        employee.setCreateUser(BaseContext.getCurrentId());
//
//        //设置修改时间
//        employee.setUpdateTime(LocalDateTime.now());

        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);

        //将密码隐藏
        employee.setPassword("******");
        return employee;
    }

    /**
     * 编辑员工信息
     *
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();

        BeanUtils.copyProperties(employeeDTO, employee);

        //设置修改人个时间
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);
    }

    /**
     * 员工修改密码
     */
    @Override
    public void passwordEdit(PasswordEditDTO passwordEditDTO) {
        //获得当前员工得id
        passwordEditDTO.setEmpId(BaseContext.getCurrentId());
        //根据id和旧密码尝试查询数据
        Employee employee = employeeMapper.getById(passwordEditDTO.getEmpId());
        //如果没有查出来 并且旧密码与员工查出来得密码不一致
        if (employee == null || !employee.getPassword().equals(DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes()))) {
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
        }

        //如果有这个员工的话就修改密码信息
        passwordEditDTO.setNewPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));    //md5加密
        employee.setPassword(passwordEditDTO.getNewPassword());
        employeeMapper.update(employee);
    }

}
